package com.lufan.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 混流工具类
 */
@Component
public class MixAudioAndVideoUtil {
    
    @Value("${ffmpeg.path:ffmpeg}")
    private String ffmpegPath;
    
    @Autowired
    private FFmpegChecker ffmpegChecker;

    public String muxVideoAndAudio(String videoPath, String audioPath, String outputPath) throws Exception {
        File videoFile = new File(videoPath);
        File audioFile = new File(audioPath);
        
        if (!videoFile.exists()) {
            throw new Exception("视频文件不存在: " + videoPath);
        }
        if (!audioFile.exists()) {
            throw new Exception("音频文件不存在: " + audioPath);
        }
        
        if (!ffmpegChecker.isFFmpegAvailable()) {
            throw new Exception("FFmpeg 不可用，请检查配置和安装: " + ffmpegPath);
        }
        
        List<String> command = new ArrayList<>();
        command.add(ffmpegPath);
        command.add("-i");
        command.add(videoPath);
        command.add("-i");
        command.add(audioPath);
        command.add("-c:v");
        command.add("copy");
        command.add("-c:a");
        command.add("aac");
        command.add("-strict");
        command.add("experimental");
        command.add("-y");
        command.add(outputPath);
        
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.redirectErrorStream(true);

        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new Exception("FFmpeg 处理失败，退出码: " + exitCode);
            }

            File outputFile = new File(outputPath);
            if (!outputFile.exists() || outputFile.length() == 0) {
                throw new Exception("输出文件未创建或为空");
            }
            
            return outputPath;
            
        } catch (Exception e) {
            throw new Exception("视频和音频合并失败: " + e.getMessage());
        }
    }
}
